<template>
  <div v-loading="loading" element-loading-text="模型生成中...">

    <el-tabs style="width: 100%;" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="梁肋操作" name="first">
        <el-form  ref="form" label-width="80px">
          <div class="selectItem">
            <div class="color-bar" style="background-color: rgb(192, 20, 255);"></div>
            <div class="selectTitle" >
              <el-radio v-model="radio" label="1">选择梁</el-radio>
            </div>
            <div class="selectedItem"  v-for="(item, index) in beams" :key="index">
              <span>{{item.name}}</span>
              <span @click="removeBeam(index)">×</span>
            </div>
          </div>
          <el-form-item label="梁宽">
            <el-input size="small" v-model.number="beamWidth" type="number" placeholder="请输入内容">
              <i slot="suffix" style="font-style:normal; color: #606266;margin-right: 5px">mm</i>
            </el-input>
          </el-form-item>
          <div class="selectItem">
            <div class="color-bar" style="background-color: rgb(192, 20, 255);"></div>
            <div class="selectTitle" >
              <el-radio v-model="radio" label="2">选择肋</el-radio>
            </div>
            <div class="selectedItem"  v-for="(item, index) in ribs" :key="index">
              <span>{{item.name}}</span>
              <span @click="removeRib(index)">×</span>
            </div>
          </div>
          <el-form-item label="肋宽">
            <el-input size="small" v-model.number="ribWidth" type="number" placeholder="请输入内容">
              <i slot="suffix" style="font-style:normal; color: #606266;margin-right: 5px">mm</i>
            </el-input>
          </el-form-item>
          <el-form-item label="肋厚">
            <el-input size="small" v-model.number="ribThickness" type="number" placeholder="请输入内容">
              <i slot="suffix" style="font-style:normal; color: #606266;margin-right: 5px">mm</i>
            </el-input>
          </el-form-item>
          <div>
            <div style="margin-top: 10px;text-align: center;">
              <el-button type="primary" size="small" @click="createSkeleton">确定</el-button>
              <el-button size="small"  @click="closeDialog">关闭</el-button>
            </div>
          </div>
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="缘条、桁条操作" name="second">
        <el-form  ref="form" label-width="80px">
<!--          <div class="selectItem">-->
<!--            <div class="color-bar" style="background-color: rgb(192, 20, 255);"></div>-->
<!--            <div class="selectTitle" >-->
<!--              <el-radio v-model="radio" label="3">选择基准面</el-radio>-->
<!--            </div>-->
<!--            <div class="selectedItem"  v-for="(item, index) in basicsFaces" :key="index">-->
<!--              <span>{{item.name}}</span>-->
<!--              <span @click="removeBasicsFace(index)">×</span>-->
<!--            </div>-->
<!--          </div>-->
          <div class="selectItem">
            <div class="color-bar" style="background-color: rgb(192, 20, 255);"></div>
            <div class="selectTitle" >
              <el-radio v-model="radio" label="4">选择桁条路径</el-radio>
            </div>
            <div class="selectedItem"  v-for="(item, index) in flangePoints" :key="index">
              <span>{{item.name}}</span>
              <span @click="removeFlangePoints(index)">×</span>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px;text-align: center;">
              <el-button type="primary" size="small" @click="createFlange">生成</el-button>
              <el-button size="small"  @click="closeDialog">关闭</el-button>
            </div>
          </div>
          <div class="selectItem">
            <div class="color-bar" style="background-color: rgb(192, 20, 255);"></div>
            <div class="selectTitle" >
              <el-radio v-model="radio" label="5">选择缘条路径</el-radio>
            </div>
            <div class="selectedItem"  v-for="(item, index) in stringerPoints" :key="index">
              <span>{{item.name}}</span>
              <span @click="removeStringerPoints(index)">×</span>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px;text-align: center;">
              <el-button type="primary" size="small" @click="createStringer">生成</el-button>
              <el-button size="small"  @click="closeDialog">关闭</el-button>
            </div>
          </div>
        </el-form>

      </el-tab-pane>

    </el-tabs>



  </div>
</template>

<script>
  import {
    Axis,
    CrownCADPlugin,
    Direction,
    PluginFunctionType,
    Point,
    PluginEventType, PluginCADToolFunctionType
  } from "../../../../nodeApp/static/lib/crowncad-plugin-sdk-0.0.1";
  export default {
    name: "SkeletonTool",
    data() {
      return {
        activeName: 'first',
        loading: false,
        minHeight: 300,
        radio:'1',
        beams:[],
        ribs: [],
        beamWidth:1.5,
        ribWidth:1.5,
        ribThickness:0.2,
        basicId:[],
        ribIds:[],
        beamIds:[],
        beamIds1:[],
        boolIds:[],
        basicsFaces:[],
        flangePoints:[],
        stringerPoints:[]
      }
    },
    async mounted() {
      //创建插件对象
      this.crownCADPlugin = new CrownCADPlugin();
      //设置CrownCAD平台地址
      this.crownCADPlugin.setParentOrigin(window.url);
      //.设置与CrownCAD平台尝试建立连接的次数
      this.crownCADPlugin.setMaxAttempt(5);
      //设置插件在CrownCAD平台显示的尺寸
      this.crownCADPlugin.setLayout(300, 300, 600);

      // 发送与CrownCAD平台建立连接的请求
      await this.crownCADPlugin.connect()
      // 设置对话框长宽高
      await this.crownCADPlugin.request.execFunction(PluginFunctionType.LAYOUT, { minWidth: 300, width: 300, maxHeight: this.minHeight})

      // 选择元素监听函数
      this.subscribeElementPick()
      this.crownCADPlugin.command.clearCommand();

    },
    methods: {
      //关闭对话框
      closeDialog() {
        this.crownCADPlugin.request.execFunction(PluginCADToolFunctionType.CLOSEACTIVECMD, null);
      },
      // 增加对话框高度
      async addHeight() {
        this.minHeight= this.minHeight + 28
        await this.crownCADPlugin.request.execFunction(PluginFunctionType.LAYOUT, { minWidth: 310, width: 310, maxHeight: this.minHeight})
      },

      // 减少对话框高度
      async minusHeight() {
        this.minHeight= this.minHeight - 28
        await this.crownCADPlugin.request.execFunction(PluginFunctionType.LAYOUT, { minWidth: 310, width: 310, maxHeight: this.minHeight})
      },

      async createSkeleton() {
        this.basicId= []
        for (let i = 0; i < this.beams.length; i++) {
          this.basicId.push(await this.createBasicPlane(this.beams[i].id,0.5*this.beamWidth,'梁基准面'+ i,0))
          this.basicId.push(await this.createBasicPlane(this.beams[i].id,0.5*this.beamWidth,'梁基准面1'+ i,1))

        }


        for (let i = 0; i < this.beams.length; i++) {
          this.beamIds.push(await this.createThicken(this.beams[i].id, this.beamWidth,2,'加厚'+ i))
        }


        this.ribIds= []
        for (let i = 0; i < this.ribs.length; i++) {
          this.ribIds.push(await this.createThicken(this.ribs[i].id, this.ribWidth,2,'加厚'+ (i + this.beams.length)))
        }


        this.beamIds1= [...this.beamIds]
        for (let i = 0; i < this.ribIds.length; i++) {
          console.log(i);
          let tempId = await this.createBooleanUnion([...this.beamIds1,this.ribIds[i]],'布尔交'+ i)
          if(!tempId) {
            return;
          }
          //await this.delay(1000);
          await this.createCutSplit(tempId, this.basicId[0],'分割0' + i)
          //await this.delay(1000);
          let res = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割0' + i]);
          if(!res) {
            return;
          }
          let res1 = await this.crownCADPlugin.query.getElementsByEntityId(res.data.entities[0].id);
          if(!res1) {
            return;
          }
          let tempFaceId= 0
          res1.data.elements.forEach(el=>{
            if(el.type===19&& Math.round(el.params.normal[0])=== 0&& Math.round(el.params.normal[1])=== 0&& Math.round(el.params.normal[2]) ===1) {

              tempFaceId= el.id
            }
          })

          await this.createShell([tempFaceId],this.ribThickness,'抽壳0' + i)

          await this.createCutSplit(res.data.entities[1].id, this.basicId[1],'分割1' + i)
          //await this.delay(1000);
          let fres = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割1' + i]);
          if(!fres) {
            return;
          }
          this.beamIds1= []
          this.beamIds1.push(fres.data.entities[0].id)

          await this.createCutSplit(fres.data.entities[1].id, this.basicId[2],'分割2' + i)
          //await this.delay(1000);
          let gres = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割2' + i]);
          if(!gres) {
            return;
          }

          let gres1 = await this.crownCADPlugin.query.getElementsByEntityId(gres.data.entities[0].id);
          if(!gres1) {
            return;
          }
          let tempFaceId1= 0
          gres1.data.elements.forEach(el=>{
            if(el.type===19&& Math.round(el.params.normal[0])=== 0&& Math.round(el.params.normal[1])=== 0&& Math.round(el.params.normal[2]) ===1) {

              tempFaceId1= el.id
            }
          })
          await this.createShell([tempFaceId1],this.ribThickness,'抽壳1' + i)

          await this.createCutSplit(gres.data.entities[1].id, this.basicId[3],'分割3' + i)
          //await this.delay(1000);
          let hres = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割3' + i]);
          if(!hres) {
            return;
          }

          this.beamIds1.push(hres.data.entities[0].id)
          let hres1 = await this.crownCADPlugin.query.getElementsByEntityId(hres.data.entities[1].id);
          if(!hres1) {
            return;
          }
          let tempFaceId2= 0
          hres1.data.elements.forEach(el=>{
            if(el.type===19&& Math.round(el.params.normal[0])=== 0&& Math.round(el.params.normal[1])=== 0&& Math.round(el.params.normal[2]) ===1) {

              tempFaceId2= el.id
            }
          })
          await this.createShell([tempFaceId2],this.ribThickness,'抽壳2' + i)

          // await this.createCutSplit(this.ribIds[i], this.basicId[1],'分割1' + i)
          // await this.createCutSplit(this.ribIds[i], this.basicId[2],'分割1' + i)
          // await this.createCutSplit(this.ribIds[i], this.basicId[3],'分割1' + i)

        }

        // return
        //
        // for (let i = 0; i < this.ribIds.length; i++) {
        //
        //   await this.createCutSplit(this.ribIds[i], this.basicId[0],'分割1' + i)
        //   let res1 = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割1' + i]);
        //
        //   let res3 = await this.crownCADPlugin.query.getElementsByEntityId(res1.data.entities[0].id);
        //
        //
        //   let tempFaceId= 0
        //
        //   res3.data.elements.forEach(el=>{
        //     if(el.type===19&& Math.round(el.params.normal[0])=== 0&& Math.round(el.params.normal[1])=== 0&& Math.round(el.params.normal[2]) ===1) {
        //
        //       tempFaceId= el.id
        //     }
        //   })
        //
        //
        //   await this.createShell([tempFaceId],this.ribThickness,'抽壳1' + + i)
        //
        //   await this.createCutSplit(res1.data.entities[1].id, this.basicId[1],'分割2' + i)
        //   let res2 = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割2' + i]);
        //
        //   let res4 = await this.crownCADPlugin.query.getElementsByEntityId(res2.data.entities[0].id);
        //
        //
        //   let tempFaceId2= 0
        //
        //   res4.data.elements.forEach(el=>{
        //     if(el.type===19&& Math.round(el.params.normal[0])=== 0&& Math.round(el.params.normal[1])=== 0&& Math.round(el.params.normal[2]) ===1) {
        //
        //       tempFaceId2= el.id
        //     }
        //   })
        //
        //   await this.createShell([tempFaceId2],this.ribThickness,'抽壳2' + + i)
        //
        //
        //   let res5 = await this.crownCADPlugin.query.getElementsByEntityId(res2.entities[1].id);
        //
        //
        //   let tempFaceId3= 0
        //
        //   res5.data.elements.forEach(el=>{
        //     if(el.type===19&& Math.round(el.params.normal[0])=== 0&& Math.round(el.params.normal[1])=== 0&& Math.round(el.params.normal[2]) ===1) {
        //
        //       tempFaceId3= el.id
        //     }
        //   })
        //
        //   await this.createShell([tempFaceId3],this.ribThickness,'抽壳3' + + i)
        // }

        // let res = await this.crownCADPlugin.query.getEntitiesByFeatureNames([this.ribIds[0]]);

        // await this.createCutSplit(res.entities[0].id, this.basicId[0],'分割')
        //
        // let res1 = await this.crownCADPlugin.query.getEntitiesByFeatureNames(['分割']);


      },

      subscribeElementPick () {

        this.crownCADPlugin.event.subscribeElementPickEvent(res => {
        // this.crownCADPlugin.request.subscribeEvent(PluginEventType.ELEMENTPICK, res => {
          if(res.element.length) {

            if(this.radio==='1') {
              if(!this.beams.length) {
                this.beams.push(res.element[0].element)
                this.addHeight()
              } else if(this.beams[this.beams.length- 1].id!==res.element[0].element.id) {
                this.beams.push(res.element[0].element)
                this.addHeight()
              }

            } else if(this.radio==='2') {
              if(!this.ribs.length) {
                this.ribs.push(res.element[0].element)
                this.addHeight()
              } else if(this.ribs[this.ribs.length- 1].id!==res.element[0].element.id) {
                this.ribs.push(res.element[0].element)
                this.addHeight()
              }
            } else if(this.radio==='3') {
              if(!this.basicsFaces.length) {
                this.basicsFaces.push(res.element[0].element)
                this.addHeight()
              }
            } else if(this.radio==='4') {

              if(!this.flangePoints.length) {
                this.flangePoints.push(res.element[0].element)
                this.addHeight()
              } else if(this.flangePoints[this.flangePoints.length- 1].id!==res.element[0].element.id) {
                this.flangePoints.push(res.element[0].element)
                this.addHeight()
              }
            } else if(this.radio==='5') {
              if(!this.stringerPoints.length) {
                this.stringerPoints.push(res.element[0].element)
                this.addHeight()
              } else if(this.stringerPoints[this.stringerPoints.length- 1].id!==res.element[0].element.id) {
                this.stringerPoints.push(res.element[0].element)
                this.addHeight()
              }
            }
          }
        })
      },

      async createBasicPlane(faceId, len, name,reverse) {
        this.crownCADPlugin.command.clearCommand();
        await this.crownCADPlugin.command.datum.createPlaneByDistanceIncrement({
          faceId: faceId,
          invertNormal: 0, paralDis: Math.abs(len), reverse: reverse
        },name);

        await this.crownCADPlugin.command.execute();
        return await this.getEntityId(name)
      },

      async getEntityId(name) {
        this.crownCADPlugin.command.clearCommand();
        // 获取草图1的featuresid
        let res= await this.crownCADPlugin.query.getFeaturesByNames([name])
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: [name]})
	      if(!res || !res?.data?.features || res.data.features.length <= 0) {
          return null;
	      }
        // 获取草图1的entityid
        let res1= await this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
        // let res1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
        // 拉伸草图1的圆


        return res1.data.entities[0].id
      },

      async getFeatureId(name) {
        this.crownCADPlugin.command.clearCommand();
        // 获取草图1的featuresid
        let res= await this.crownCADPlugin.query.getFeaturesByNames([name])
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: [name]})
        return res.data.features[0]?.id
      },

      async createThicken(faceId,thickness,outward,name) {
        this.crownCADPlugin.command.clearCommand();
        await this.crownCADPlugin.command.solid.thickenIncrement({
          thickenSurfaceId: faceId, thickness: thickness, outward: outward, },name)
        await this.crownCADPlugin.command.execute();
        return await this.getEntityId(name)
      },

      async createBooleanUnion(entitys, name) {
        this.crownCADPlugin.command.clearCommand();
        await this.crownCADPlugin.command.solid.booleanUnionIncrement({
          entitys: entitys },name)

        await this.crownCADPlugin.command.execute();
        return await this.getEntityId(name)
      },

      async createCutSplit(solidId,cutSurfaceId,name) {
        this.crownCADPlugin.command.clearCommand();
        await this.crownCADPlugin.command.solid.cutSplitIncrement({
          solidId, cutSurfaceId, },name)

        await this.crownCADPlugin.command.execute();
      },

      async createShell(removeFaces,thickness,name) {
        this.crownCADPlugin.command.clearCommand();
        await this.crownCADPlugin.command.solid.createShellIncrement({
          removeFaces,
          thickness,
          outward: 0},name)
        await this.crownCADPlugin.command.execute();

      },

      delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      },

      async createFlange() {

        // let res = await this.crownCADPlugin.query.getElementsByIds([this.flangePoints[0].id]);


        for (let i = 0; i < this.flangePoints.length; i++) {

          let point= this.flangePoints[i].params.startPoint

          //清空command
          this.crownCADPlugin.command.clearCommand();
          //创建草图，命名为sketch1
          this.crownCADPlugin.command.sketch.createSketch({sketchName: 'sketch' + i, datumId: 8});

          this.crownCADPlugin.command.sketch.createSketchLine({
            startPoint: new Point(point[0],point[1],0),
            endPoint:new Point(point[0]- 2,point[1],0)
          })
          this.crownCADPlugin.command.sketch.createSketchLine({
            startPoint: new Point(point[0],point[1],0),
            endPoint:new Point(point[0],point[1]> 0? point[1]-2:point[1]+ 2  ,0)
          })
          //退出草图
          this.crownCADPlugin.command.sketch.exitSketch();
          //实现草图操作，参数true会覆盖之前的草图，不传则不会
          await this.crownCADPlugin.command.execute()

          let sketchId= await this.getEntityId('sketch' + i)
          await this.createSweepSurface(0,sketchId,[this.flangePoints[i].id], '扫描曲面' + i)
        }
        //清空command
        // this.crownCADPlugin.command.clearCommand();
        // //创建草图，命名为sketch1
        // this.crownCADPlugin.command.sketch.createSketch({sketchName: 'sketch' + Math.floor(Math.random() * 10), datumId: 8});
        //
        // this.crownCADPlugin.command.sketch.createSketchLine({
        //   startPoint: new Point(0,0,0),
        //   endPoint:new Point( this.mP['0'],this.mP['1'],0)
        // })
        // //退出草图
        // this.crownCADPlugin.command.sketch.exitSketch();
        // //实现草图操作，参数true会覆盖之前的草图，不传则不会
        // await this.crownCADPlugin.command.execute()
      },

      async createStringer() {
        // let res = await this.crownCADPlugin.query.getElementsByIds([this.stringerPoints[0].id]);


        for (let i = 0; i < this.stringerPoints.length; i++) {

          let point = this.stringerPoints[i].params.startPoint

          //清空command
          this.crownCADPlugin.command.clearCommand();
          //创建草图，命名为sketch1
          this.crownCADPlugin.command.sketch.createSketch({sketchName: 'sketchs' + i, datumId: 8});

          this.crownCADPlugin.command.sketch.createSketchLine({
            startPoint: new Point(point[0], point[1], 0),
            endPoint: new Point(point[0] - 2, point[1], 0)
          })
          this.crownCADPlugin.command.sketch.createSketchLine({
            startPoint: new Point(point[0], point[1], 0),
            endPoint: new Point(point[0] + 2, point[1], 0)
          })
          //退出草图
          this.crownCADPlugin.command.sketch.exitSketch();
          //实现草图操作，参数true会覆盖之前的草图，不传则不会
          await this.crownCADPlugin.command.execute()

          let sketchId = await this.getEntityId('sketchs' + i)
          await this.createSweepSurface(0, sketchId, [this.stringerPoints[i].id], '扫描曲面s' + i)
        }
      },

      async createSweepSurface(sweepType,sweepProfile,sweepPath,name) {
        this.crownCADPlugin.command.clearCommand();
        this.crownCADPlugin.command.surface.sweepSurface({
          sweepType,
          sweepProfile,
          sweepPath,
          profileDirection: 2,
        },name)

        await this.crownCADPlugin.command.execute();
      },

      // 移除肋直线
      removeRib(index) {
        this.ribs.splice(index, 1);
        this.minusHeight()
      },

      removeBeam(index) {
        this.beams.splice(index, 1);
        this.minusHeight()
      },
      removeBasicsFace() {
        this.basicsFaces.splice(index, 1);
        this.minusHeight()
      },
      removeFlangePoints(index) {
        this.flangePoints.splice(index, 1);
        this.minusHeight()
      },
      removeStringerPoints(index) {
        this.stringerPoints.splice(index, 1);
        this.minusHeight()
      }
    },

  }
</script>

<style scoped>
  >>> .el-form-item {
    margin-bottom: 5px!important;
  }
  >>> .el-form-item__label {
    margin-bottom: 5px!important;
  }

  >>> .el-form-item {
    height: 32px!important;
  }
  >>> .el-form-item__label {
    line-height: 32px !important;
  }
  .selectItem {
    background-color: #d6eaff;
    color: #212529;
    border: 1px solid #6e7177;
    border-radius: .2rem;
    margin: .5rem .25rem;
    padding: .25rem .25rem .25rem .5rem;
    font-size: 12px;
    position: relative;
    cursor: pointer;
  }
  .color-bar {
    border-radius: 0 0 10px 0;
    height: 10px;
    left: 0;
    position: absolute;
    top: 0;
    -webkit-transition: .2s;
    transition: .2s;
    width: 10px;
  }
  .selectTitle {
    height: 24px;
    line-height: 24px;
  }
  .selectedItem {
    margin-left: 20px;
    padding: 5px 15px 5px 5px;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
  }
  .selectedItem:hover {
    background-color: rgba(0,0,0,.1)/* 鼠标悬浮时的背景颜色 */
  }
</style>
